<?php

namespace App\Http\Managers;

// use Cache;
use Illuminate\Cache\CacheManager;
use App\Models\Company;
use App\Models\Area;
use Illuminate\Auth\AuthManager;

class CompanyManager
{
	protected $cache;
	
	public static $companyCacheKey = 'company:default';

	public static $areaCacheKey = 'company:area';
	
    public function __construct(CacheManager $cache, AuthManager $auth) {
		$this->cache = $cache;
		$this->auth = $auth;
    }
	
	// 默认公司
	public function getCompanyCache() {
		return $this->cache->get(self::$companyCacheKey, function () {
			return Company::limit(1)->get()->first()->toArray();
		});
	}
	
	// 获取公司信息
	public function getCompanyField($field="Co_ID") {
		$company = $this->getCompanyCache();
		return array_get($company, $field);
	}
	
	// 区域缓存键
	protected function getAreaCacheKey() {
		$cid = data_get($this->auth->user(), 'Co_ID');
		return self::$areaCacheKey.':'. ($cid?$cid:$this->getCompanyField());
	}
	
	// 默认区域
	public function getAreaCache() {
		return $this->cache->get($this->getAreaCacheKey(), function () {
			$info = Area::where('Fid', '>', 0)->limit(1)->get()->first();
			return $info?$info->toArray():[];
		});
	}
	
	// 获取区域信息
	public function getAreaField($field="AreaID") {
		$area = $this->getAreaCache();
		return array_get($company, $area);
	}

	//缓存区域数据
	public function cacheAreaData($data) {
		$this->cache->forever($this->getAreaCacheKey(), $data);
	}

	//缓存公司数据
	public function cacheCompanyData($data) {
		$this->cache->forever(self::$companyCacheKey, $data);
	}

	
}
